//
//  SNADView.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/15.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "SNADModel.h"
#import "SNADView.h"
#import "SDCycleScrollView.h"
#import "SNADViewController.h"
@interface SNADView()<SDCycleScrollViewDelegate>
/** mmButton */
@property(weak, nonatomic) UIButton * deleteButton;
/** View */
@property (weak, nonatomic) SDCycleScrollView *cycleScrollView;
/** self.imageURLStrings */
@property (nonatomic,strong) NSMutableArray<NSString *> * imageURLStrings;
/** count */
@property (nonatomic,strong) NSNumber * countNumber;
/** NSMutableArray * imageNames */
@property (nonatomic,strong) NSMutableArray * imageNames;
@end
@implementation SNADView

- (void)receivedUPDateADNotification:(NSNotification *)notify
{
    [[ZXHTTPManager sharedManager] advertisementdownWithCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        if (error) {
            NSLog(@"error = %@",error);
            return ;
        }
        NSLog(@"%@",jsonDict);
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        NSArray<NSDictionary *> * arr = jsonDict[@"result"];
        for(int i = 0; i < arr.count; i++) {
            NSDictionary * dict =  arr[i];
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",dict[@"resourceId"]];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            NSString * fileName = [NSString stringWithFormat:@"AD%02d.png",i];
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            [imageNames addObject:kCachePath(fileName)];
        }
        
        self.cycleScrollView.imageURLStringsGroup = self.imageNames;
//              self.cycleScrollView.imageURLStringsGroup = @[
//                                                              @"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3215910746,2290723362&fm=21&gp=0.jpg",
//                                                              @"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3195266601,881181399&fm=21&gp=0.jpg"
//                                                              ];

    }];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedUPDateADNotification:   ) name:@"UPDateADNotification" object:nil];
        
        self.backgroundColor = [UIColor orangeColor];
        [self addObserver:self forKeyPath:@"countNumber" options:NSKeyValueObservingOptionNew context:nil];
        
        [self addCycleScrollView:frame];
        
        [self addDeleteButton:self frame:frame];
    }
    return self;
}
- (void)addCycleScrollViewORIGINAL:(CGRect)frame
{
    [[ZXHTTPManager sharedManager] advertisementdownWithCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        logError;
        
        NSLog(@"jsonDict = %@",jsonDict);
        
        SNADModel *adModel = [SNADModel mj_objectWithKeyValues:jsonDict];
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        for(int i = 0; i < adModel.result.count; i++) {
            
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",adModel.result[i].resourceId];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        //        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        //        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                NSString * fileName = [NSString stringWithFormat:@"AD_%02d.png",i];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                    [imageNames addObject:kCachePath(fileName)];
                    NSLog(@"fileName = %@",kCachePath(fileName));
                    //                    self.countNumber = @(imageNames.count);
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }];
    
    
    NSArray *imageNames = @[@"ad1",
                            ];
    
    //    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) delegate:self placeholderImage:[UIImage imageNamed:@""]];
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) shouldInfiniteLoop:YES imageNamesGroup:imageNames];
    cycleScrollView.delegate = self;
    self.cycleScrollView = cycleScrollView;
    cycleScrollView.autoScroll = NO;
    //    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleNone;
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
    //    cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [self addSubview:cycleScrollView];
    
}


- (void)addCycleScrollView:(CGRect)frame
{
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) delegate:self placeholderImage:[SNUtils imageWithString:@"f5f5f5"]];
    self.cycleScrollView = cycleScrollView;
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleNone;
    cycleScrollView.autoScroll = NO;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:cycleScrollView];
    
    [[ZXHTTPManager sharedManager] advertisementdownWithCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        if (error) {
            NSLog(@"error = %@",error);
            return ;
        }
        NSLog(@"%@",jsonDict);
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        NSArray<NSDictionary *> * arr = jsonDict[@"result"];
        for(int i = 0; i < arr.count; i++) {
            NSDictionary * dict =  arr[i];
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",dict[@"resourceId"]];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                NSString * fileName = [NSString stringWithFormat:@"AD%02d.png",i];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                    [imageNames addObject:kCachePath(fileName)];
                    NSLog(@"fileName = %@",kCachePath(fileName));
                    self.countNumber = @(imageNames.count);
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"countNumber"]) {
        NSInteger count = [change[@"new"] integerValue];
        if(self.imageURLStrings.count == count){
            NSLog(@"change = %@",change[@"new"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.cycleScrollView.imageURLStringsGroup = self.imageNames;
            });
            
            NSString * keyString = [NSString stringWithFormat:@"%@", self.observationInfo];
            if ([keyString containsString:@"countNumber"]) {
                NSLog(@"首页轮播图监听者...close");
                [self removeObserver:self forKeyPath:@"countNumber"];
            }
            // [self removeObserver:self forKeyPath:@"countNumber"];
        }
    }
}


- (void)addDeleteButton:(UIView *)view frame:(CGRect)frame
{
    
    UIButton * deleteButton = ({
        UIButton * button = [[UIButton alloc] init];
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"圆角矩形 1 拷贝 2"] forState:UIControlStateNormal];
        
        [button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat w = 13;
        button.frame = CGRectMake(frame.size.width - w - 5, 5, w, w);
        
        [view addSubview:button];
        
        button;
    });
    
    self.deleteButton = deleteButton;
    
}
-(void)btnClicked : (UIButton *)sender {
    NSLog(@"%s", __func__);
    
    [self removeFromSuperview];
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    
}
@end
